<template>
  <div id="container" style="height: 100%"></div>
</template>

<script lang="ts" setup>
  import { onMounted } from 'vue';
  import * as echarts from 'echarts/core';
  import {
    TitleComponent,
    TitleComponentOption,
    TooltipComponent,
    TooltipComponentOption,
    LegendComponent,
    LegendComponentOption,
  } from 'echarts/components';
  import { GraphChart, GraphSeriesOption } from 'echarts/charts';
  import { CanvasRenderer } from 'echarts/renderers';
  import { graphData } from './data';

  type EChartsOption = echarts.ComposeOption<
    TitleComponentOption | TooltipComponentOption | LegendComponentOption | GraphSeriesOption
  >;

  interface GraphNode {
    symbolSize: number;
    label?: {
      show?: boolean;
    };
  }

  const loadGraphData = (graph) => {
    echarts.use([TitleComponent, TooltipComponent, LegendComponent, GraphChart, CanvasRenderer]);
    const chartDom = document.getElementById('container')!;
    const myChart = echarts.init(chartDom);
    let option: EChartsOption;
    myChart.showLoading();
    myChart.hideLoading();

    graph.nodes.forEach(function (node: GraphNode) {
      node.label = {
        show: node.symbolSize > 30,
      };
    });
    option = {
      title: {
        text: 'Les Miserables',
        subtext: 'Default layout',
        top: 'bottom',
        left: 'right',
      },
      tooltip: {},
      legend: [
        {
          // selectedMode: 'single',
          data: graph.categories.map(function (a: { name: string }) {
            return a.name;
          }),
        },
      ],
      animationDuration: 1500,
      animationEasingUpdate: 'quinticInOut',
      series: [
        {
          name: 'Les Miserables',
          type: 'graph',
          layout: 'none',
          data: graph.nodes,
          links: graph.links,
          categories: graph.categories,
          roam: true,
          label: {
            position: 'right',
            formatter: '{b}',
          },
          lineStyle: {
            color: 'source',
            curveness: 0.3,
          },
          emphasis: {
            focus: 'adjacency',
            lineStyle: {
              width: 10,
            },
          },
        },
      ],
    };

    myChart.setOption(option);
  };

  onMounted(() => {
    loadGraphData(graphData);
  });
</script>
